package com.codes.controller;

import com.codes.core.common.result.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2020/6/9 15:08
 * @Created by peanut
 */

@Slf4j
@Api(tags = "上传")
@RestController
@RequestMapping("/upload")
public class UploadCtr {



    @Value("${file-save-path}")
    private String fileSavePath;

    @Value("${file-save-local-path}")
    private String fileSaveLocalPath;


    /**
     * 设备图片上传
     * @return {Result}
     */
    @RequestMapping(value = "/savefile", method = {RequestMethod.POST})
    @ResponseBody
    public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String prefix="";
        String dateStr="";
        String uploadDir = fileSavePath;
        String saveUrl = fileSaveLocalPath;
        //保存上传
        try{
            if(file!=null){
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                dateStr = String.valueOf(new Date().getTime());
              //  String filepath = request.getServletContext().getRealPath("/static") + uploadDir + dateStr + "." + prefix;
                String filepath =  uploadDir + dateStr + "." + prefix;
                filepath = filepath.replace("\\", "/");
                File files=new File(filepath);
                //打印查看上传路径
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
            }
        }catch (Exception e){
        }

       // String fileUrl = "../../../static"+uploadDir + dateStr + "." + prefix;
        String fileUrl = saveUrl + dateStr + "." + prefix;
        Map<String,Object> map=new HashMap<>();
        map.put("src",fileUrl);
        return Result.success(map);

//        Map<String,Object> map2=new HashMap<>();
//        Map<String,Object> map=new HashMap<>();
//        map.put("code",0);
//        map.put("msg","");
//        map.put("data",map2);
//        map2.put("src",fileUrl);
//        return map;


    }


}